package com.kucun.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.sdlc.com.database.BaseDaoInterface;
import org.sdlc.com.database.bean.CglibDynaBean;
import org.sdlc.com.database.impl.MysqlBaseDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.JsonArray;
import com.kucun.bean.Goods;
import com.kucun.bean.Page;
import com.kucun.bean.Repertory;
import com.kucun.bean.Users;
import com.kucun.service.GoodsService;
import com.kucun.service.RepertoryService;
import com.kucun.util.GsonUtils;
import com.kucun.util.JsonTreeData;
import com.kucun.util.TreeNodeService;
import com.kucun.util.TreeNodeUtil;
import com.kucun.util.UID;
import com.times.util.DateUtils;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


@Controller
@RequestMapping("/repertory")
public class RepertoryController {

	@Autowired
	private RepertoryService repertoryService;

	
	/**
	 * 
	 * @param request
	 * @return
	 * @throws IOException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@RequestMapping("/getallrepertory.html")
	public String getAllUser(HttpServletRequest request,HttpServletResponse response) throws IOException, IllegalAccessException, InvocationTargetException{
		 BaseDaoInterface basedao=MysqlBaseDaoImpl.getInstance();
		 List<CglibDynaBean> lists=null;
		 lists= basedao.getListCglib("select * from repertory ");
		 List<JsonTreeData> treeDataList = new ArrayList<JsonTreeData>();
		 for (CglibDynaBean cglib : lists) {
			 Repertory treeData = new Repertory();
			// BeanUtils.copyProperties(cglib, treeData);
	            treeData.setId(cglib.getValue("id").toString());
	            treeData.setPid(cglib.getValue("parentid")!=null?cglib.getValue("parentid").toString():null);
	            treeData.setAttributes(cglib);
	            treeData.setText(cglib.getValue("titles").toString());
	            treeData.setAddress((String) cglib.getValue("address"));
	            treeData.setManegername((String)cglib.getValue("manegername"));
	            treeData.setManegertell((Integer) (cglib.getValue("manegertell")!=null?cglib.getValue("manegertell"):null));
	            treeData.setIsused((Integer) cglib.getValue("isused"));
	            treeDataList.add(treeData);
		 }
		 List<JsonTreeData> newTreeDataList = TreeNodeUtil.getfatherNode(treeDataList);
	     JSONArray jsonObject = JSONArray.fromObject(newTreeDataList);
	    PrintWriter pw = response.getWriter();
	    //System.out.println(jsonObject.toString()); 
	    pw.write(jsonObject.toString());
	    
	     //System.out.println(new GsonUtils().ChagneDateFormat(newTreeDataList));
		
		/*Page page1=new Page();
		page1.setI(rows*(page-1));
		page1.setRows(rows);*/
/*		Map jsonMap = new HashMap();//定义map  
		List<Repertory> list = repertoryService.
		jsonMap.put("total",repertoryService.getCount().getTotal());//total键 存放总记录数，必须的  
        jsonMap.put("rows",list);//rows键 存放每页记录 list  
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);//格式化result   一定要是JSONObject  
        PrintWriter pw = response.getWriter();
        pw.write(jsonObject.toString());*/

		return null;
	}
	
	/**
	 * @param user
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/addrepertory.html")
	public String addrepertory(Repertory goods,HttpServletRequest request,HttpServletResponse response) throws IOException{
		String tag=request.getParameter("tag");
		Users user=(Users)request.getSession().getAttribute("user");
		int s=0;
		PrintWriter pw = response.getWriter();
		if("1".equals(tag)){
			int ss=repertoryService.updateByPrimaryKeySelective(goods);
			if(ss>0){
				 pw.write("ok");
			}else{
				 pw.write("err");
			}
		}else{
			String billon="WP"+UID.next();
			goods.setId(null);
			goods.setBackup(billon);
			s=repertoryService.save(goods);
			if(s>0){
				 pw.write("ok");
			}else{
				 pw.write("err");
			}
		}
		return null;
	}
	/**
	 * @param user
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/updategoods.html")
	public String updateUser(String goodsname,Repertory user,HttpServletRequest request,HttpServletResponse response) throws IOException{
		int s=repertoryService.updateGoodsForDel(goodsname);
		PrintWriter out = response.getWriter();
		if(s>0){
			 out.write("ok");
		}else{
			 out.write("err");
		}
		return null;
	}
	/**
	 * @param id
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	@RequestMapping("/delrepertory.html")
	public void delRepertory(Integer id,HttpServletRequest request,HttpServletResponse response) throws IOException{
		System.out.println(id);
		BaseDaoInterface basedao=MysqlBaseDaoImpl.getInstance();
		StringBuffer sb=new StringBuffer();
		List<Map<String, Object>> s=new TreeNodeService().doTreeData(id,basedao,sb);
		System.out.println(sb);
		String result = "err";
		String ids=sb.toString()+id;
		if(repertoryService.delRepertoryForDel(ids)>0){
			result = "ok";
		}
		

			PrintWriter out = response.getWriter();
			out.write(result);
		

	}
	
	@RequestMapping("/exit.html")
	public String clear(HttpServletRequest request){
		request.getSession(true).setAttribute("user",null);
		return "/login";
	}
	
}
